package ext.vpde.cadvaulting.service;

import com.ptc.wvs.server.publish.PublishServiceEvent;
import ext.vpde.cadvaulting.util.WpHelperUtility;
import java.io.PrintStream;
import java.io.Serializable;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentMaster;
import wt.events.KeyedEvent;
import wt.fc.Persistable;
import wt.fc.WTObject;
import wt.services.*;
import wt.type.*;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.*;
import wt.vc.wip.WorkInProgressServiceEvent;


public class StandardWhirlpoolListenerService extends StandardManager implements WhirlpoolListenerService, Serializable {



   private static final String RESOURCE = "ext.vpde.cadvaulting.service.servicesResource";
   private static final String CLASSNAME = StandardWhirlpoolListenerService.class.getName();

    private static boolean DEBUG;

   static
   {
      try
      {
         WTProperties properties = WTProperties.getLocalProperties();
         DEBUG = properties.getProperty("ext.vpde.cadvaulting.verbose", false);
      }
      catch (Throwable t)
      {
          t.printStackTrace();
	  }
   }


   public String getConceptualClassname() {
      return CLASSNAME;
   }


   public static StandardWhirlpoolListenerService newStandardWhirlpoolListenerService()
            throws WTException {

      StandardWhirlpoolListenerService instance = new StandardWhirlpoolListenerService();
      instance.initialize();
      return instance;
   }


   protected void performStartupProcess()
            throws ManagerException {
      System.out.println("WhirlpoolListenerService starting");
      if (DEBUG) System.out.println("Starting process of registering listener with method server");

      WhirlpoolListener whirlpoolNewVersionListener = new WhirlpoolListener(this.getConceptualClassname());
      WhirlpoolListener whirlpoolCheckInListener = new WhirlpoolListener(this.getConceptualClassname());
      WhirlpoolListener whirlpoolPublishListener = new WhirlpoolListener(this.getConceptualClassname());

      getManagerService().addEventListener
           (
            whirlpoolCheckInListener,
            WorkInProgressServiceEvent.generateEventKey(WorkInProgressServiceEvent.POST_CHECKIN)
            );
      getManagerService().addEventListener
           (
            whirlpoolNewVersionListener,
            VersionControlServiceEvent.generateEventKey( VersionControlServiceEvent.NEW_VERSION)
            );
      getManagerService().addEventListener
           (
            whirlpoolPublishListener,
            PublishServiceEvent.generateEventKey( PublishServiceEvent.PUBLISH_SUCCESSFUL)
            );

      //super.performStartupProcess();
   }


   protected void performStoreUpdateEvent( Persistable target, KeyedEvent event )
            throws WTException {
         if(DEBUG) System.out.println("*** Event Type = " + event.getEventType());
         if( target instanceof EPMDocument )
         {
           if ( event.getEventType().equals( VersionControlServiceEvent.NEW_VERSION))
           {
               // NEW VERSION EVENT
               //handleNewVersionEvent( target );
           } else if(event.getEventType().equals(WorkInProgressServiceEvent.POST_CHECKIN ))
           {
               // POST CHECKIN EVENT
               handlePostCheckinEvent( target );

           } else if(event.getEventType().equals(PublishServiceEvent.PUBLISH_SUCCESSFUL ))
           {
               // PUBLISH SUCCESSFUL EVENT
               handlePublishEvent( target );

           }
         }
   }

   private void handleNewVersionEvent( Object target )
      throws WTException
   {
	   if(DEBUG)
	   {
		   System.out.println("*** Begin WhirlpoolEventListener.handleNewVersionEvent() ***");
		   System.out.println("*** target= " + target + "\t" + ((WTObject)target).getDisplayIdentity());
	   }
       if( target instanceof EPMDocument )
       {
		   String softType = wt.type.TypedUtility.getExternalTypeIdentifier(target);
		   if (DEBUG){
			   System.out.println ("*** BEGIN NEW WTDOCUMENT/EPMDOCUMENT VERSION EVENT ***");
			   System.out.println ("*** Type= " + softType );
		   }
		   // Check to see if object is using standard revisioning scheme, if not apply standard
	       if ( softType.endsWith("DefaultEPMDocument") && !WpHelperUtility.isStandard((Versioned)target) )
    	   {
			   String table = (target instanceof WTDocument)?"WTDOCUMENT":"EPMDOCUMENT";
			   //WpHelperUtility.setVersion((Versioned)target, table);
    	   }
	   }
   }

   private void handlePostCheckinEvent( Object target )
      throws WTException
   {
	   target = VersionControlHelper.service.getLatestIteration((Iterated)target, false);
	   if(DEBUG)
	   {
		   System.out.println("*** Begin WhirlpoolEventListener.handleCheckInEvent() ***");
		   System.out.println("*** target= " + target + "\t" + ((WTObject)target).getDisplayIdentity());
	   }
       if( target instanceof EPMDocument )
       {
		   String softType = wt.type.TypedUtility.getExternalTypeIdentifier(target);
		   if (DEBUG){
			   System.out.println ("*** BEGIN NEW WTDOCUMENT/EPMDOCUMENT VERSION EVENT ***");
			   System.out.println ("*** Type= " + softType );
		   }
		   // Check to see if object is of type drawing, if so attach pdf with watermark
	       if ( softType.endsWith("DefaultEPMDocument") &&  (((EPMDocument)target).getDocType().toString()).equals("CADDRAWING") )
    	   {
			   try
			   {
				  /* boolean published = false;
				   int i = 0;
				   int timeout =  ext.vpde.cadvaulting.pdf.PDFUtility.getMaxPDFGen();
				   System.out.println ("********* PDF Generation Timeout: " + timeout + " ************");
				   while (!published)
				   {
					   //check to see if the drw pdf has been generated
					   published = ext.vpde.cadvaulting.pdf.PDFUtility.isPublished((EPMDocument)target, "default");
					   if(!published)
					   {
						   System.out.println("*****WAITING FOR DRAWINGS TO PUBLISH*****");
						   Thread.currentThread().sleep(30000);
						   if (i++>timeout)
							   System.out.println("Unable to generate PDF for " + ((wt.fc.WTObject)target).getDisplayIdentity() + "\nPlease notify system administrator") ;
					   }
					   else ext.vpde.cadvaulting.pdf.PDFUtility.processPdf((EPMDocument)target,"default", "NOT RELEASED", false, true);
				   }*/
			   } catch (Exception e){e.printStackTrace();}
			   //WpHelperUtility.setVersion((Versioned)target, table);
    	   }
	   }
   }

   private void handlePublishEvent( Object target )
      throws WTException
   {
		   System.out.println("*** Begin WhirlpoolEventListener.handlePublishEvent() ***");
		   System.out.println("*** target= " + target + "\t" + ((WTObject)target).getDisplayIdentity());
   }

   class WhirlpoolListener extends ServiceEventListenerAdapter
   {
      //Listener Constructor
      public WhirlpoolListener (String manager_name)
      {
        super (manager_name);
        if (DEBUG) System.out.println("Whirlpool Listener Started");
      }
      public void notifyVetoableEvent( Object eventObject )
            throws Exception
      {
        if (!(eventObject instanceof KeyedEvent)) return;
        KeyedEvent myevent=(KeyedEvent) eventObject;
        System.out.println("****** EVENT THROWN: " + myevent.getEventType() );
        Object target=myevent.getEventTarget();
        if ( (myevent.getEventType().equals("NEW_VERSION")) ||
             (myevent.getEventType().equals("POST_CHECKIN")) ||
             (myevent.getEventType().equals("PUBLISH_SUCCESSFUL"))   )
        {
           try
           {
              performStoreUpdateEvent((Persistable)target, myevent);
           }
           catch (WTException wte)
           {
              wte.printStackTrace();
           }
        }
      }
   }

}
